package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyDaEQianBao;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeDaEQianBao;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

/**
 * 大鹅钱包采安心分期28  8位掩码md5
 * @ Author 江小游
 * @ Date 2025/6/4 14:43
 */
@ApiPlan(productId = "235", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatDaEQianBaoPhoneMaskConvert implements ApiPlatformPhoneMaskConvertHandler {
    private static final String CHANNEL_CODE = "POH1PV";
    private static final String KEY = "yB8IvpajVxKIlAVb";
    private static final String IV = "yB8IvpajVxKIlAVb";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataChangeMessage) throws Exception {
        // 撞库流程
        ApiPlatDataExchangeDaEQianBao apiPlatDataExchange = new ApiPlatDataExchangeDaEQianBao();
        // 扩展
        com.ts.api.module.api.convert.core.utils.ApiFieldConverter apiFieldConverter = com.ts.api.module.api.convert.core.utils.ApiFieldConverter.create(apiDataChangeMessage);
        // 姓名
        apiPlatDataExchange.setName("默认姓名");
        // 掩码8位
        apiPlatDataExchange.setMaskPhone(apiDataChangeMessage.getPhoneMask());
        // MD5
        apiPlatDataExchange.setMd5Phone(apiDataChangeMessage.getPhoneMd5());
        // 省
        apiPlatDataExchange.setProvince(apiDataChangeMessage.getProvinceName());
        // 市
        apiPlatDataExchange.setCityName(apiDataChangeMessage.getCity().replace("市", ""));
        // 用户ip
        apiPlatDataExchange.setUserIp(apiDataChangeMessage.getIp());
        // 年龄
        apiPlatDataExchange.setAge(apiDataChangeMessage.getAge());
        // 借款额度 1万以下 || 1万-5万  ||  5万-10万 ||  10万-20万 || 20万以上
        String loanAmount = ChooseEq.create(apiDataChangeMessage.getLoanAmount())
                .when("1", "1万以下")
                .when("2", "5万-10万")
                .when("3", "10万-20万")
                .when("4", "20万以上")
                .end("1万以下");
        apiPlatDataExchange.setLoanAmount(loanAmount);
        // 房产情况 有/无
        apiPlatDataExchange.setHouse(apiFieldConverter.hasRealEstateInfoToStr());
        // 车辆情况 有/无
        apiPlatDataExchange.setCar(apiFieldConverter.hasCarInfoToStr());
        // 公积金 六个月以上|六个月以下|无
        String providentFund = ChooseEq.create(apiDataChangeMessage.getProvidentFund())
                .when("1", "无")
                .when("2", "六个月以下")
                .when("3", "六个月以上")
                .when("4", "六个月以下")
                .end("无");
        apiPlatDataExchange.setAccumulation(providentFund);
        // 芝麻分 700以上|650-699以内|600-649以内|600以下
        String sesame = ChooseEq.create(apiDataChangeMessage.getSesameCredit())
                .when("1", "600以下")
                .when("2", "600-649以内")
                .when("3", "650-699以内")
                .when("4", "700以上")
                .end("600以下");
        apiPlatDataExchange.setSesameSeed(sesame);
        /*
           信用情况（逾期）
           1.无逾期
           2.有逾期
         */
        String overdue = ChooseEq.create(apiDataChangeMessage.getOverdue())
                .when("1", "无逾期")
                .when("2", "有逾期")
                .when("3", "有逾期")
                .end("无逾期");
        apiPlatDataExchange.setOverdueSituation(overdue);
        // 职业 上班族|公务员-事业单位|私营企业主|自由职业
        String career = ChooseEq.create(apiDataChangeMessage.getCareer())
                .when("1", "上班族")
                .when("2", "自由职业")
                .when("3", "私营企业主")
                .when("4", "公务员-事业单位")
                .when("5", "私营企业主")
                .end("自由职业");
        apiPlatDataExchange.setProfession(career);
        // 社保缴纳 有/无
        apiPlatDataExchange.setSocialSecurity(apiFieldConverter.hasSocialSecurityToStr());
        // 保险保单 有/无
        apiPlatDataExchange.setInsurance(apiFieldConverter.hasInsurancePolicyToStr());
        // 花呗额度 有/无
        String hbLimit = ChooseEq.create(apiDataChangeMessage.getHbLimit())
                .when("1", "无")
                .when("2", "有")
                .when("3", "有")
                .when("4", "有")
                .when("5", "有")
                .end("无");
        apiPlatDataExchange.setHuabei(hbLimit);
        // 白条额度 有/无
        String btLimit = ChooseEq.create(apiDataChangeMessage.getBtLimit())
                .when("1", "无")
                .when("2", "有")
                .when("3", "有")
                .when("4", "有")
                .when("5", "有")
                .end("无");
        apiPlatDataExchange.setJdQuota(btLimit);
        //  性别 1:男 0:女
        String sex = ChooseEq.create(apiDataChangeMessage.getSex())
                .when("0", "1")
                .when("1", "0")
                .end("1");
        apiPlatDataExchange.setSex(sex);
        // 加密
        AES aes = AES.createCbc(KEY.getBytes(), IV.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatDataExchange));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("encryptData", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyMessage) throws Exception {
        //  进件流程
        ApiPlatApplyDaEQianBao apiPlatApply = new ApiPlatApplyDaEQianBao();
        // 扩展
        com.ts.api.module.api.convert.core.utils.ApiFieldConverter apiFieldConverter = com.ts.api.module.api.convert.core.utils.ApiFieldConverter.create(apiApplyMessage);
        // 姓名
        apiPlatApply.setName(apiApplyMessage.getUserName());
        // 电话
        apiPlatApply.setUserPhone(apiApplyMessage.getPhone());
        // 省
        apiPlatApply.setProvince(apiApplyMessage.getProvinceName());
        // 市
        apiPlatApply.setCityName(apiApplyMessage.getCity().replace("市", ""));
        // 年龄
        apiPlatApply.setAge(apiApplyMessage.getAge());
        // 用户ip
        apiPlatApply.setUserIp(apiApplyMessage.getIp());
        // 借款额度 1万以下 || 1万-5万  ||  5万-10万 ||  10万-20万 || 20万以上
        String loanAmount = ChooseEq.create(apiApplyMessage.getLoanAmount())
                .when("1", "1万以下")
                .when("2", "5万-10万")
                .when("3", "10万-20万")
                .when("4", "20万以上")
                .end("1万以下");
        apiPlatApply.setLoanAmount(loanAmount);
        // 房产情况 有/无
        apiPlatApply.setHouse(apiFieldConverter.hasRealEstateInfoToStr());
        // 车辆情况 有/无
        apiPlatApply.setCar(apiFieldConverter.hasCarInfoToStr());
        /*
          公积金
          1.无公积金
          2.缴纳6个月以下
          3.缴纳6个月以上
          4.有公积金
        */
        String providentFund = ChooseEq.create(apiApplyMessage.getProvidentFund())
                .when("1", "无")
                .when("2", "六个月以下")
                .when("3", "六个月以上")
                .when("4", "六个月以下")
                .end("无");
        apiPlatApply.setAccumulation(providentFund);
        // 芝麻分 700以上|650-699以内|600-649以内|600以下
        String sesame = ChooseEq.create(apiApplyMessage.getSesameCredit())
                .when("1", "600以下")
                .when("2", "600-649以内")
                .when("3", "650-699以内")
                .when("4", "700以上")
                .end("600以下");
        apiPlatApply.setSesameSeed(sesame);
        /*
           信用情况（逾期）
           1.无逾期
           2.当前有逾期
           3.一年以内无逾期
         */
        String overdue = ChooseEq.create(apiApplyMessage.getOverdue())
                .when("1", "无逾期")
                .when("2", "有逾期")
                .when("3", "有逾期")
                .end("无逾期");
        apiPlatApply.setOverdueSituation(overdue);
        // 职业 上班族|公务员-事业单位|私营企业主|自由职业
        String career = ChooseEq.create(apiApplyMessage.getCareer())
                .when("1", "上班族")
                .when("2", "自由职业")
                .when("3", "私营企业主")
                .when("4", "公务员-事业单位")
                .when("5", "私营企业主")
                .end("上班族");
        apiPlatApply.setProfession(career);
        // 社保缴纳 有/无
        apiPlatApply.setSocialSecurity(apiFieldConverter.hasSocialSecurityToStr());
        // 保险保单 有/无
        apiPlatApply.setInsurance(apiFieldConverter.hasInsurancePolicyToStr());
        // 花呗额度 有/无
        String hbLimit = ChooseEq.create(apiApplyMessage.getHbLimit())
                .when("1", "无")
                .when("2", "有")
                .when("3", "有")
                .when("4", "有")
                .when("5", "有")
                .end("无");
        apiPlatApply.setHuabei(hbLimit);
        // 白条额度 有/无
        String btLimit = ChooseEq.create(apiApplyMessage.getBtLimit())
                .when("1", "无")
                .when("2", "有")
                .when("3", "有")
                .when("4", "有")
                .when("5", "有")
                .end("无");
        apiPlatApply.setJdQuota(btLimit);
        //  性别 1:男 0:女
        String sex = ChooseEq.create(apiApplyMessage.getSex())
                .when("0", "1")
                .when("1", "0")
                .end("1");
        apiPlatApply.setSex(sex);
        // 返回的撞库id
        apiPlatApply.setTraceId(apiApplyMessage.getApplyId());
        // 加密
        AES aes = AES.createCbc(KEY.getBytes(), IV.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(apiPlatApply));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_CODE);
            newMap.put("encryptData", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) throws Exception {
        //  进件返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        //  根据文档响应判断
        return RespPlatformPhoneMaskApply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }

    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) {
        //  撞库返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        JSONObject resData = JsonUtils.get(respJson).getJSONObject("data");
        if (ValidParam.isNull(resData)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();

        //  解析
        RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();
        BigDecimal price = resData.getBigDecimal("price");
        String productName = resData.getString("exhibitionName");
        String orderId = resData.getString("traceId");
        String companyName = resData.getString("exhibitionName");

        result.setDisplayName(companyName);
        //  返回原价
        BigDecimal sourcePrice = price.multiply(new BigDecimal("1.25")).setScale(2, RoundingMode.HALF_UP);
        result.setPrice(sourcePrice);
        result.setProductName(productName);
        result.setApplyId(orderId);

        listRespPlatformPhoneMaskDataExchange.add(result);
        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);
        return respPlatformMultiPhoneMaskDataExchange;
    }
}
